package com.antler.smt.admin.service.impl;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.antler.smt.admin.mapper.*;
import com.antler.smt.constant.DateTimeConstant;
import com.antler.smt.constant.OrderConstant;
import com.antler.smt.entity.OrderEntity;
import com.antler.smt.entity.RequirementEntity;
import com.antler.smt.entity.SupplierEntity;
import com.antler.smt.entity.UserEntity;
import com.antler.smt.enums.ResultCodeEnum;
import com.antler.smt.response.admin.GetUserListResp;
import com.antler.smt.response.base.Result;
import com.antler.smt.service.portal.MatchUserService;
import com.antler.smt.utils.DateUtil;
import com.antler.smt.utils.LogUtil;
import com.antler.smt.utils.SmsUtil;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 匹配项目专员 TODO
 *
 * @author zhangyi
 * @date 2018/4/10 9:09
 */
@Service
public class MatchUserServiceImpl implements MatchUserService {

    /**
     * 日志
     */
    private static Logger log = LogUtil.get();

    @Autowired
    private MatchUserMapper matchUserMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderEntityMapper orderEntityMapper;

    @Autowired
    public RequirementEntityMapper requirementEntityMapper;

    @Autowired
    private SupplierEntityMapper supplierEntityMapper;

    /**
     * 获取一个匹配的项目专员实体
     *
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = DateTimeConstant.MINUTE_S, rollbackFor = Exception.class)
    public Result<GetUserListResp> getMatchUserInfo(long orderId) {
        Result result = null;

        GetUserListResp userInfo = getUser();

        //返回随机匹配的项目专员实体
        result = new Result(userInfo);
        OrderEntity orderEntity1 = orderEntityMapper.selectByPrimaryKey(orderId);
        //发送短信给项目专员
        Result result1 = sendMessageForUser(orderEntity1.getRequirementId(), userInfo);

        //更新订单
        OrderEntity orderEntity = new OrderEntity();
        //添加订单id
        orderEntity.setId(orderId);
        //添加项目专员id
        orderEntity.setConnectUserId(userInfo.getId());
        //更新订单状态
        orderEntity.setStatus(OrderConstant.ORDER_WAIT_JOIN_SUPPLIER);
        //初始化更新时间
        orderEntity.setUpdateTime(DateUtil.stampToDate(System.currentTimeMillis()));
        //更新订单信息
        int i = orderEntityMapper.updateByPrimaryKeySelective(orderEntity);

        boolean flag = (0 == i);
        if (flag) {
            return new Result(ResultCodeEnum.APPEND_DATA_ERROR);
        } else {
            return result;
        }
    }

    /**
     * 随机返回项目专员信息
     *
     * @return
     */
    @Override
    public Result<GetUserListResp> getUserInfo() {
        List<Long> userIdList = matchUserMapper.getUserIdList();
        int random = (int)Math.floor(Math.random()*userIdList.size());
        return new Result (matchUserMapper.getUserInfo(userIdList.get(random)));
    }
    public GetUserListResp getUser(){
        //下单的数量
        long number = 0;
        //最终匹配的项目专员id
        long userId = 0;
        //获取id集合
        List<Long> userIdList = matchUserMapper.getUserIdList();

        //存储项目专员的id值和处理单量
        Map<Long, Long> userMap = new LinkedHashMap<>();

        for (int i = 0; i < userIdList.size(); i++) {
            number = orderInfoMapper.getUserDisposeOrderList(userIdList.get(i));
            userMap.put(userIdList.get(i), number);
        }
        Set<Long> longs = userMap.keySet();
        Iterator<Long> iterator = longs.iterator();
        while (iterator.hasNext()) {
            Long key = iterator.next();
            Long value = userMap.get(key);
            //获取订单数最少的项目专员id
            if (number >= value) {
                number = value;
                userId = key;
            }
        }
        //项目专员的个数
        int  userSize = userIdList.size();
        //各个项目专员的订单量相同
        if (userId == 0) {
            //随机分配
            userId = (long) Math.random() * userSize + 1;
        }
        //获取单数少的项目专员
        GetUserListResp userInfo = matchUserMapper.getUserInfo(userId);
        return  userInfo;
    }

    /**
     * 发送短信给项目专员
     *
     * @param requirementId
     * @param userInfo
     */
    public Result sendMessageForUser(Long requirementId,GetUserListResp userInfo ){
        Result result = null;
        RequirementEntity requirementEntity = requirementEntityMapper.selectByPrimaryKey(requirementId);
        //发送短信至项目专员
            SendSmsResponse sendSmsResponse = SmsUtil.sendPickUpSms(userInfo.getMobile(),
                    userInfo.getRealName(),
                    new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(DateUtil.stampToDate(System.currentTimeMillis())),
                    "已经对接到"+requirementEntity.getName());
            if (sendSmsResponse.getCode().equalsIgnoreCase("OK") && sendSmsResponse.getMessage().equalsIgnoreCase("OK")) {
                result = new Result(ResultCodeEnum.OPERATION_SUCCESS);
            } else {
                result = new Result(ResultCodeEnum.APPEND_DATA_ERROR);
            }
        return result;
    }

    @Override
    public Result<UserEntity> matchBusinessAffairs(long requirementId, long memberId) {
        return null;
    }
    @Override
    public Result<GetUserListResp> getMatchUser(long requirementId, long memberId) {
        return null;
    }
}
